package com.qf.filter;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

/**
 * @author 10202
 * @version V1.0
 * @Project xiaomi
 * @Package ${PACKAGE_NAME}
 * @Date 2023/4/13 17:41
 */
@WebFilter(filterName = "AutoLoginFilter",urlPatterns = "/index.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        User user=(User) request.getSession().getAttribute("user");
        if(user!=null){
            chain.doFilter(req,resp);
            return;
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
               String userinfo = cookie.getValue();
               userinfo=new String(Base64.getUrlDecoder().decode(userinfo),"utf-8") ;
                String[] arr = userinfo.split("#");

                UserService userService=new UserServiceImpl();
                try {
                    User login = userService.login(arr[0], arr[1]);
                    request.getSession().setAttribute("user",login);

                } catch (Exception e) {
                    cookie.setPath(request.getContextPath());
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }

            }

        }



        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
